<template>
  <div>
    <el-container>
      <!--       aside -->
      <!--      100vh为整个窗口高度-->
      <el-aside style="width:200px; min-height: 100vh;background-color: #15293b">
        <div style="height: 60px; color: aliceblue; display: flex; align-items: center;justify-content: center" >
          <img :src="require('@/assets/library.jpg')" style="height: 80%;">
        </div>
        <!--        侧边导航栏-->

        <el-menu style="border: none" :default-active="$route.path" router background-color="#15293b" text-color="rgba(255,255,255,0.65)" active-text-color="#FFF"  @select="handleSelect">
          <el-menu-item index="/login">
            <template slot="title">
              <i class="el-icon-right"></i>
              <span>登录界面</span>
            </template>
          </el-menu-item>
          <el-menu-item index="/home">
            <template slot="title">
              <i class="el-icon-s-marketing"></i>
              <span>系统首页</span>
            </template>
          </el-menu-item>
          <el-menu-item index="/about">
            <template slot="title">
              <i class="el-icon-user"></i>
              <span>用户管理</span>
            </template>
          </el-menu-item>
          <el-menu-item index="/product">
            <template slot="title">
              <i class="el-icon-collection"></i>
              <span>书籍管理</span>
            </template>
          </el-menu-item>
          <el-submenu>
            <template slot="title">
              <i class="el-icon-loading"></i>
              <span></span>
            </template>
          </el-submenu>
        </el-menu>
      </el-aside>


      <el-container>
        <!-- header -->
        <el-header style="display: flex; align-items: center; justify-content: space-between; height: 60px; background-color: #2c3e50; color: white;">
          <div style="text-align: center; width: 100%;">图书管理系统</div>
          <el-tooltip class="item" effect="dark" content="新消息" placement="top" style="margin-right: 40px">
            <el-badge  class="item">
              <el-button @click="notice()" size="mini" type="primary" icon="el-icon-message-solid" circle></el-button>
            </el-badge>
          </el-tooltip>
          <el-tooltip class="item" effect="dark" content="个人中心" placement="top" style="margin-right: 20px">
            <el-badge  class="item">
              <el-button @click="personCenter()" size="mini" type="primary" icon="el-icon-user-solid" circle></el-button>
            </el-badge>
          </el-tooltip>
        </el-header>

        <!-- main -->
        <el-main>

          <div style="display: flex; justify-content: space-around; align-items: center;">
            <el-card style="width: 700px;height: 350px" class="box-card custom-card" shadow="hover">
            <div id="categoryPieChart" style="flex: 1; height: 400px;"></div>
            </el-card>

            <el-card style="width: 700px;height: 350px" class="box-card custom-card" shadow="hover">
            <div id="pieChart" style="flex: 1; height: 350px;"></div>
            </el-card>
          </div>
          <div style="display: flex; justify-content: center; align-items: center;">
            <el-card class="box-card custom-card" style="width: 320px; height: 230px; "  shadow="hover">
              <div class="card-content">
                <h2 class="custom-title">书籍剩余</h2>
                <p class="total-surplus">{{ totalSurplus }}</p>
              </div>
            </el-card>
            <el-card style="width: 1150px;height: 230px" class="box-card custom-card" shadow="hover">
            <div ref="chart" style="width: 1100px; height: 230px;"></div>
            </el-card>
          </div>
        </el-main>
      </el-container>
    </el-container>
  </div>
</template>

<script>
import * as echarts from 'echarts';
import axios from "axios";
import Cookies from "js-cookie";
export default {
  name:'HemoView',
  data() {
    return {
      username:'',
      password:'',
      myChart: null,
      fullData: [],
      tableData: [],
      itemNumber: 0,
      totalSurplus: 0, // 存储surplus的总和
      is_admin:false,
    };
  },
  // created() {
  //   // 在组件创建时获取查询参数并设置user
  //   this.username = this.$route.query.username ;
  //   this.password = this.$route.query.password ;
  //   // 如果URL中没有提供username，你可以选择设置一个默认值
  // },
  methods: {
    notice(){
      if(!this.is_admin){
        this.$router.push({ name: 'notice'});
      }
      else {
        this.$router.push({ name: 'adminnotice'});
      }
    },
    personCenter(){
      const message = "this is admin";
      this.$router.push({ name: 'person', params: { message }});
    },
    handleSelect(index) {
      const routeData = {
        path: index,
        query: {
          username: this.username,
          password: this.password,
        }
      };

      this.$router.push(routeData).catch(err => {
        // 如果路由跳转发生错误，你可以在这里处理
        console.error('Route navigation failed:', err);
      });
    },
    async fetchData() {
      try {
        // 用于获取数据的API URL
        const url = 'http://127.0.0.1:5000/v1/bookReport/month_borrow_book';
        const response = await axios.get(url);

        // 假定服务器返回的数据结构如前所述
        const result = response.data;

        // 解析数据
        const parsedData = JSON.parse(result.data);
        this.formatData(parsedData);
      } catch (error) {
        console.error('Error fetching data:', error);
      }
    },
    formatData(dataItems) {
      // Reduce 函数用于按月累加 borrow_count
      const groupedData = dataItems.reduce((acc, cur) => {
        const { month, borrow_count } = cur;
        acc[month] = (acc[month] || 0) + borrow_count;
        return acc;
      }, {});

      // 画图函数传入月份和对应的借阅次数
      this.drawChart(Object.keys(groupedData), Object.values(groupedData));
    },
    drawChart(months, borrowCounts) {
      // 通过ref获取DOM元素，并初始化echarts实例
      this.myChart = echarts.init(this.$refs.chart);

      // 配置echarts option
      const options = {
        title: {
          text: '每月借阅总览'
        },
        tooltip: {
          trigger: 'axis'
        },
        xAxis: {
          type: 'category',
          data: months
        },
        yAxis: {
          type: 'value'
        },
        series: [{
          data: borrowCounts,
          type: 'line',
          smooth: true
        }]
      };

      // 使用配置项和数据显示图表。
      this.myChart.setOption(options);
    },
    loadBooks() {
      axios.get("http://127.0.0.1:5000/v1/books/allBooks")
          .then((response) => {
            this.fullData = response.data.data;
            this.calculateTotalSurplus();
            console.log(this.totalSurplus)
            this.initCategoryPieChart();
          });
    },
    initCategoryPieChart() {
      // 根据 category 对书籍进行分组计算每个类别的 surplus 总和
      const categorySurplus = this.fullData.reduce((acc, cur) => {
        const { category, surplus } = cur;
        if (!acc[category]) {
          acc[category] = 0;
        }
        acc[category] += Number(surplus);
        return acc;
      }, {});

      // 使用 ECharts 初始化饼状图
      const chartDom = document.getElementById('categoryPieChart'); // 确保HTML中有这个ID的元素
      const myChart = echarts.init(chartDom);
      const option = {
        title: {
          text: '类别库存总览',
          left: 'center',
        },
        tooltip: {
          trigger: 'item',
        },
        legend: {
          orient: 'vertical',
          left: 'left',
        },
        series: [
          {
            name: '类别',
            type: 'pie',
            radius: '50%',
            data: Object.entries(categorySurplus).map(([name, value]) => ({ name, value })),
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: 'rgba(0, 0, 0, 0.5)',
              },
            },
          },
        ],
      };
      myChart.setOption(option);
    },
    calculateTotalSurplus() {
      this.totalSurplus = this.fullData.reduce((accumulator, book) => accumulator + Number(book.surplus), 0);
    },
    fetchBookReport() {
      axios.get("http://127.0.0.1:5000/v1/bookReport/month_borrow_book")
          .then((response) => {
            const bookData = JSON.parse(response.data.data); // 解析数据
            this.totalBorrowCount = bookData.reduce((acc, curr) => acc + curr.borrow_count, 0);
            this.initPieChart();
          });
    },
    initPieChart() {
      const chartDom = document.getElementById('pieChart');
      const myChart = echarts.init(chartDom);
      const option = {
        title: {
          text: '库存和借阅总览',
          left: 'center',
        },
        tooltip: {
          trigger: 'item',
        },
        legend: {
          orient: 'vertical',
          left: 'left',
        },
        series: [
          {
            name: '访问来源',
            type: 'pie',
            radius: '50%',
            data: [
              { value: this.totalSurplus, name: '总库存' },
              { value: this.totalBorrowCount, name: '总借阅次数' },
            ],
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: 'rgba(0, 0, 0, 0.5)'
              }
            }
          }
        ]
      };
      myChart.setOption(option);
    }
  },

  mounted() {

    this.loadBooks();
    this.fetchBookReport(); // 在组件加载的时候调用
    this.fetchData();
    this.username = Cookies.get('username');
    this.password = Cookies.get('password');
    this.is_admin = Cookies.get('is_admin');
  },
  beforeDestroy() {
    if (this.myChart) {
      this.myChart.dispose();
    }
  }
};

</script>

<style>
.el-menu--inline .el-menu--item{
  background-color: #000c17 !important;
}
.el-menu-item:hover,.el-submenu__title:hover{
  color: #FFF !important;
}
.text {
  font-size: 14px;
}

.item {
  padding: 18px 0;
}
.custom-card {
  background-color: #f5f5f5;
  border-radius: 10px;
  padding: 20px;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1); /* 阴影 */
  border: 1px solid #ebebeb; /* 边框 */
}

.card-content {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}

.total-surplus {
  font-size: 36px;
  color: #15293b;
  font-weight: bold;
}
.custom-title {
  font-size: 24px; /* 自定义标题字体大小 */
  color: #15293b; /* 自定义标题颜色 */
  margin-bottom: 10px; /* 标题与数据之间的间距 */
}
.el-card{
  margin: 10px;
  border-radius: 20px;
  border-color: #C0C4CC;
}
.custom-card:hover {
  background-color: #e6e6e6;
  transform: translateY(5px);
}

</style>
